package com.kkwrite.regimen.provider.controller.captcha;

import com.kkwrite.regimen.common.constant.DeletedEnum;
import com.kkwrite.regimen.common.entity.dto.captcha.CaptchaDTO;
import com.kkwrite.regimen.common.entity.dto.captcha.CaptchaQuery;
import com.kkwrite.regimen.common.entity.dto.captcha.CodeDTO;
import com.kkwrite.regimen.provider.service.captcha.CaptchaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;

/** 
 * 验证码服务
 *
 * @author Soosky Wang
 * @date 2018年7月19日 上午11:24:00 
 * @version 1.0.0
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

	private static final Logger logger = LoggerFactory.getLogger(CaptchaController.class);
	
	@Resource(name = "captchaService")
	private CaptchaService captchaService;
	
	@GetMapping("/getcaptcha")
	public CodeDTO getCaptcha(CaptchaQuery captchaQuery) {
		if (logger.isDebugEnabled()) {
			logger.debug("CaptchaController.getCaptcha(), captchaQuery = " + captchaQuery);
		}
		
		CodeDTO codeDTO = new CodeDTO();
		
		CaptchaDTO captchaDTO = captchaService.getCaptcha(captchaQuery);
		if (captchaDTO == null) {
			codeDTO.setSuccess("failed");
			codeDTO.setMsg("验证码不存在！");
			return codeDTO;
		}
		
		// 判断验证码是否过期
		LocalDateTime expireTime = captchaDTO.getExpireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
		LocalDateTime currentTime = LocalDateTime.now();
		if (currentTime.isAfter(expireTime)) {
			codeDTO.setSuccess("failed");
			codeDTO.setMsg("验证码已过期！");
			return codeDTO;
		}
		
		// 判断验证码是否已经使用
		if (DeletedEnum.DELETED.getValue().equals(captchaDTO.getDeleted())) {
			codeDTO.setSuccess("failed");
			codeDTO.setMsg("验证码已被使用！");
			return codeDTO;
		}
		
		codeDTO.setSuccess("true");
		codeDTO.setData(new CodeDTO.CodeBody(captchaDTO.getCaptchaValue()));
		return codeDTO;
	}
	
}
